package com.ken.common.event.framework.processor.idempotent;

import com.ken.common.core.utils.ApplicationContextUtils;
import com.ken.common.event.apply.handle.EventHandler;
import com.ken.common.event.framework.message.EventMessage;
import com.ken.common.event.framework.processor.EventMsgPostProcessor;
import com.ken.common.event.framework.processor.idempotent.annotation.Idemportent;
import com.ken.common.event.framework.processor.idempotent.handler.IdempotentHandler;

/**
 * 消息幂等处理器
 */
public class IdempotentProcessor implements EventMsgPostProcessor {


    /**
     * 如果没有幂等注解则不做幂等处理
     * @param eventTypeStr
     * @param eventMessage
     * @param eventHandler
     * @return
     */
    @Override
    public boolean isSupport(String eventTypeStr, EventMessage eventMessage, EventHandler eventHandler) {
        return eventHandler.getClass().isAnnotationPresent(Idemportent.class);
    }

    /**
     * 幂等是实现方案
     * @param eventMessage
     * @param eventHandler
     * @return
     */
    @Override
    public boolean beginProcessor(EventMessage eventMessage, EventHandler eventHandler) {
        //获得幂等注解
        Idemportent annotation = eventHandler.getClass().getAnnotation(Idemportent.class);
        //获得指定的幂等处理器
        IdempotentHandler idempotentHandler = ApplicationContextUtils.getBean(annotation.value());
        //进行幂等校验
        boolean flag = idempotentHandler.isIdempotent(eventMessage);
        return flag;
    }
}
